package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.StageRegisterOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 阶段进度登记详情界面
 * Created by lenovo on 2016/7/4.
 */
public class StageRegisterDetailFragment extends Fragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.StageRegisterDetailFragment.EXTRA_CONTENT";
  protected static final int MAIN_THING = 0;
  protected static final int MAIN_DATE = 1;

  private EditText mEtMainThing;
  private EditText mEtMainContent;
  private ImageView mIbMainContent;
  private EditText mEtFinishContent;
  private EditText mEtRemark;
  private TextView mTvRegister;
  private TextView mTvRegisteredTime;

  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private StageRegisterOriginal.StageRegisterContent content;
  private CustomerDialog extContent;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    if (NavUtils.getParentActivityName(getActivity()) != null) {
      ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.progressRegist);
    mActivity = (BaseVolleyActivity) getActivity();
    mUser = CurrentUser.newInstance(getActivity());
    content =
        (StageRegisterOriginal.StageRegisterContent) getArguments().getSerializable(EXTRA_CONTENT);
    extContent =
        (CustomerDialog) getArguments().getSerializable(StageRegistListFragment.EXTRA_CONTENT);
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_stage_detail, container, false);
    findView(v);
    initData();
    return v;
  }

  private void findView(View v) {
    mEtMainThing = (EditText) v.findViewById(R.id.et_mainThing);
    ImageView mIbMainThing = (ImageView) v.findViewById(R.id.ib_mainThing);
    mIbMainContent = (ImageView) v.findViewById(R.id.ib_mainContent);
    mEtMainContent = (EditText) v.findViewById(R.id.et_mainContent);
    mEtFinishContent = (EditText) v.findViewById(R.id.et_finishContent);
    mEtRemark = (EditText) v.findViewById(R.id.et_remark);
    mTvRegister = (TextView) v.findViewById(R.id.tv_register);
    mTvRegisteredTime = (TextView) v.findViewById(R.id.tv_registered_time);
    mIbMainThing.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        DialogFragment dialog = new ChooseMainDialogFragment();
        FragmentManager fm = getActivity().getSupportFragmentManager();
        dialog.setTargetFragment(StageRegisterDetailFragment.this, MAIN_THING);
        dialog.show(fm, "");
      }
    });

    mIbMainContent.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if ("实际开始时间".equalsIgnoreCase(mEtMainThing.getText().toString())
            || "实际结束时间".equalsIgnoreCase(mEtMainThing.getText().toString())) {
          DialogFragment dialog = new BaseYMDTimeDialogFragment();
          FragmentManager fm = getActivity().getSupportFragmentManager();
          dialog.setTargetFragment(StageRegisterDetailFragment.this, MAIN_DATE);
          dialog.show(fm, "");
        }
      }
    });
  }

  private void initData() {
    if (content != null) {
      mEtMainThing.setText(content.getLogName());
      mEtMainContent.setText(content.getLogContent());
      mEtFinishContent.setText(content.getExcDesc());
      mEtRemark.setText(content.getRemark());
      mTvRegister.setText(content.getRegStaffName());
      mTvRegisteredTime.setText(content.getRegDate());
      if ("实际开始时间".equalsIgnoreCase(mEtMainThing.getText().toString()) || "实际结束时间".equalsIgnoreCase(
          mEtMainThing.getText().toString())) {
        mEtMainThing.setEnabled(false);
        mEtMainThing.setTextColor(Color.RED);
        mEtMainContent.setEnabled(false);
        mIbMainContent.setVisibility(View.VISIBLE);
      } else {
        mIbMainContent.setVisibility(View.GONE);
      }
    } else {
      mTvRegister.setText(mUser.getRealName());
      mTvRegisteredTime.setText(MyDateUtil.dateToString(new Date(), MyDateUtil.TYPE_DATE));
      mIbMainContent.setVisibility(View.GONE);
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_already_done, menu);
    menu.getItem(0).setTitle(R.string.save);
    menu.getItem(1).setTitle(R.string.delete);
    if (content == null) {
      menu.getItem(1).setVisible(false).setEnabled(false);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      //保存
      case R.id.menu_item_recover:
        //当前登录人是阶段负责人或项目经理是可编辑保存
        //                if ((mUser.getJobNumber()).equals(extContent.getId()) || (mUser.getJobNumber()).equals(extContent.getName())) {
        //                    if ("new".equals(extContent.getJobNo()) || "newback".equals(extContent.getJobNo()) ) {
        if (!TextUtils.isEmpty(mEtMainThing.getText().toString())) {
          volleyPostSave();
        } else {
          ToastUtil.show(R.string.completeWrite);
        }

        //                    }else {
        //                        ToastUtil.show("只有草稿和返回修改状态才能修改！");
        //                    }
        //                } else {
        //                    ToastUtil.show(R.string.pm_regist);
        //                }

        return true;
      //删除
      case R.id.menu_item_reminders:
        //当前登录人是阶段负责人或项目经理是可编辑保存
        //                if ((mUser.getJobNumber()).equals(extContent.getId()) || (mUser.getJobNumber()).equals(extContent.getName())) {

        volleyPostDelete();

        //                } else {
        //                    ToastUtil.show(R.string.pm_regist);
        //                }

        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPostSave() {
    String saveUrl = ApiConst.getAbsoluteUrl(ApiConst.ULR_STAGE_REGIST_SAVE);
    HashMap<String, String> params = new HashMap<>();
    if (content != null) {
      params.put("id", content.getId());
    }
    params.put("logName", mEtMainThing.getText().toString());
    params.put("logContent", mEtMainContent.getText().toString());
    params.put("excDesc", mEtFinishContent.getText().toString());
    params.put("remark", mEtRemark.getText().toString());
    params.put("stageId", extContent.getMemberCode());
    params.put("stageName", extContent.getDept());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(saveUrl, params, response());
  }

  private void volleyPostDelete() {
    String delUrl = ApiConst.getAbsoluteUrl(ApiConst.ULR_STAGE_REGIST_DEL);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", content.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(delUrl, params, response());
  }

  private VolleyResponse response() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(success.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            ToastUtil.show(R.string.success_operation);

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == MAIN_THING) {
      String mainThing = data.getStringExtra(ChooseMainDialogFragment.EXTRA_MAIN);
      mEtMainThing.setText(mainThing);
      if ("实际开始时间".equals(mainThing) || "实际结束时间".equals(mainThing)) {
        mEtMainThing.setTextColor(Color.RED);
        mEtMainThing.setEnabled(false);//不可编辑
        mEtMainContent.setEnabled(false);
        mIbMainContent.setVisibility(View.VISIBLE);
      } else {
        mIbMainContent.setVisibility(View.GONE);
        mEtMainThing.setEnabled(true);
        mEtMainContent.setEnabled(true);
      }
    }
    if (requestCode == MAIN_DATE) {
      Date date = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      String dateStr = MyDateUtil.dateToString(date, MyDateUtil.TYPE_DATE);
      mEtMainContent.setText(dateStr);
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static StageRegisterDetailFragment newInstance(
      StageRegisterOriginal.StageRegisterContent content, String stageId, String stageName) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(StageRegisterDetailFragment.EXTRA_CONTENT, content);
    bundle.putSerializable(StageRegistListFragment.EXTRA_SAGE_ID, stageId);
    bundle.putSerializable(StageRegistListFragment.EXTRA_SAGE_NAME, stageName);
    StageRegisterDetailFragment mfragment = new StageRegisterDetailFragment();
    mfragment.setArguments(bundle);
    return mfragment;
  }

  public static StageRegisterDetailFragment newInstance(
      StageRegisterOriginal.StageRegisterContent content, CustomerDialog extContent) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(StageRegisterDetailFragment.EXTRA_CONTENT, content);
    bundle.putSerializable(StageRegistListFragment.EXTRA_CONTENT, extContent);
    StageRegisterDetailFragment mfragment = new StageRegisterDetailFragment();
    mfragment.setArguments(bundle);
    return mfragment;
  }
}
